﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Sklep.Domain.Abstract;
using Sklep.Domain.Entities;
using Sklep.WebUI.Models;

namespace Sklep.WebUI.Controllers
{
    public class ProductController : Controller
    {
        private readonly IProductRepository _repository;
        public int PageSize = 10; //pozniej to zmienimy

        public ProductController(IProductRepository productRepository)
        {
            _repository = productRepository;
        }

        public FileContentResult GetImage(int productID)
        {
            Product prod = _repository.Products.FirstOrDefault(x => x.ProductID == productID);
            if (prod != null)
                return File(prod.ImageData, prod.ImageMimeType);
            else
                return null;

        }

        public ViewResult List(string category, int page = 1)
        {
            IEnumerable<Product> products;
            if (category == null)
                products = _repository.Products.OrderBy(x => x.ProductID).Skip((page - 1) * PageSize).Take(PageSize);
            else
                products = _repository.Products.
                    Where(p => p.Category == null || p.Category == category).OrderBy(p => p.ProductID).Skip((page - 1)*
                                                                                                            PageSize).
                    Take(PageSize);
                   

            var viewModel = new ProductListViewModel
                {
                    Products = products,
                    PagingInfo = new PagingInfo
                        {
                            CurrentPage = page,
                            ItemsPerPage = PageSize,
                            TotalItems = category == null ? _repository.Products.Count() :
                            _repository.Products.Count(x => x.Category == category)
                        },
                        CurrentCategory = category
                };

            return View(viewModel);
        }
    }
}
